package graduation.claf.inteceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import graduation.claf.tools.ResponseCode;
import graduation.claf.tools.Constant;
import graduation.claf.utils.ServerResponse;
import graduation.claf.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

//拦截器
@Component
public class ProtalLoginCheckInteceptors implements HandlerInterceptor {

    //在请求到达controller前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=====PreHandle=====");
        HttpSession session = request.getSession();
        UserVO user = (UserVO) session.getAttribute(Constant.CURRENT_USER);
        if (user != null){
            return true;
        }
        //重写Response，返回用户没有登陆信息
        try {
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            ServerResponse serverResponse = ServerResponse.createServerResponseByFail(
                    ResponseCode.USER_NOT_LOGIN.getCode(),
                    ResponseCode.USER_NOT_LOGIN.getMsg());
            //对象转json
            ObjectMapper objectMapper = new ObjectMapper();
            String info = objectMapper.writeValueAsString(serverResponse);
            printWriter.write(info);
            printWriter.flush();
            printWriter.close();
        }catch (Exception e){

        }
        return false;
    }

    //在请求处理完成后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("=====PostHandle=====");
    }

    //客户端接收到响应后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("=====AfterHandle=====");
    }
}

